package com.example.guiguiapplicatio.fragment.Fulfillment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.navigation.Navigation;

import com.example.guiguiapplicatio.api.GetdataResponseBody.GetfulfillmentAddDataApi;
import com.example.guiguiapplicatio.api.InsertFulfillmentApi;
import com.example.guiguiapplicatio.api.Interface.AllCallback;
import com.example.guiguiapplicatio.api.Interface.GetfulfillmentAddDataCallback;
import com.example.guiguiapplicatio.R;
import com.example.guiguiapplicatio.Response.FulfillmentAddData;
import com.example.guiguiapplicatio.util.ResponseBody;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.loper7.date_time_picker.dialog.CardDatePickerDialog;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import cn.refactor.lib.colordialog.PromptDialog;

public class FulfillmentitemAddFragment extends Fragment {

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private Spinner spinner_location;
    private ArrayAdapter arrayAdapter;
    //定义字符串数组,指定数组的元素
    private String[] spinner = new String[]{"1","2","3","4"};
    private String result;
    Button btn_submit;
    TextView Tv_name;
    TextView Tv_sex;
    TextView Tv_phone;
    TextView Tv_Id;
    TextView Tv_doctorsTeam;
    TextView Tv_agencies;
    TextView Tv_completions;
    EditText Tv_Efficiency;
    EditText fulfillment_Contract;
    TextView Tv_Servicename;
    TextView Tv_serviceItemsName;
    // TODO: Rename and change types of parameters
    private String idCard;
    private String servicePackagesId;
    private String serviceItemId;
    private GetfulfillmentAddDataApi getfulfillmentAddDataApi;
    private InsertFulfillmentApi insertFulfillmentApi;
    private int mYear;
    private int mMonth;
    private int mDay;
    ImageButton servic_back;

    public FulfillmentitemAddFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BreakContinueFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static FulfillmentitemAddFragment newInstance(String param1, String param2) {
        FulfillmentitemAddFragment fragment = new FulfillmentitemAddFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            idCard = getArguments().getString("idCard");
            servicePackagesId = getArguments().getString("servicePackagesId");
            serviceItemId = getArguments().getString("serviceItemId");
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_fulfillmentadd, container, false);
        TextView day_select = root.findViewById(R.id.day_select);
        TextView day_nextselect = root.findViewById(R.id.day_nextselect);
        Tv_name = root.findViewById(R.id.Tv_name);
        servic_back = root.findViewById(R.id.servic_back);
        Tv_sex = root.findViewById(R.id.Tv_sex);
        Tv_phone = root.findViewById(R.id.Tv_phone);
        Tv_Id = root.findViewById(R.id.Tv_Id);
        Tv_doctorsTeam = root.findViewById(R.id.Tv_doctorsTeam);
        Tv_agencies = root.findViewById(R.id.Tv_agencies);
        Tv_Efficiency = root.findViewById(R.id.Tv_Efficiency);
        fulfillment_Contract = root.findViewById(R.id.fulfillment_Contract);
        spinner_location=root.findViewById(R.id.spinner_location);
        Tv_Servicename = root.findViewById(R.id.Tv_Servicename);
        Tv_serviceItemsName = root.findViewById(R.id.Tv_serviceItemsName);
        btn_submit = root.findViewById(R.id.btn_submit);
        getfulfillmentAddDataApi = new GetfulfillmentAddDataApi();
        getfulfillmentAddDataApi.setCallback(getfulfillmentAddDataCallback);
        getfulfillmentAddDataApi.performgetfulfillmentAddData(idCard, servicePackagesId, serviceItemId);
        arrayAdapter=new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_item,spinner);
        spinner_location.setAdapter(arrayAdapter);
        insertFulfillmentApi = new InsertFulfillmentApi();
        spinner_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                result = parent.getItemAtPosition(position).toString();
                if(result == "1"){
                    Tv_Efficiency.setText("25%");
                }
                if(result == "2"){
                    Tv_Efficiency.setText("50%");
                }
                if(result == "3"){
                    Tv_Efficiency.setText("75%");
                }
                if(result == "4"){
                    Tv_Efficiency.setText("100%");
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        day_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Calendar currentDate = Calendar.getInstance();
                mYear = currentDate.get(Calendar.YEAR);
                mMonth = currentDate.get(Calendar.MONTH);
                mDay = currentDate.get(Calendar.DAY_OF_MONTH);
                day_select.setText(String.format(Locale.getDefault(), "%04d-%02d-%02d", mYear, mMonth + 1, mDay));

            }
        });
        day_nextselect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new CardDatePickerDialog.Builder(getContext())
                        .setDisplayType(0, // 显示年
                                1, // 显示月
                                2)
                        .showBackNow(false)
                        .setTitle("选择时间")
                        .setOnChoose("确定", aLong -> {
                            Date selectedDate = new Date(aLong);
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
                            String formattedDate = sdf.format(selectedDate);
                            day_nextselect.setText(formattedDate);
                        }).build().show();
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                insertFulfillmentApi.setInsertFulfillmentCallback(new AllCallback() {
                    @Override
                    public void onSuccess(ResponseBody<Object> responseBody) {
                        if (responseBody.getCode() == 200) {
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    new PromptDialog(getContext())
                                            .setDialogType(PromptDialog.DIALOG_TYPE_SUCCESS)
                                            .setAnimationEnable(true)
                                            .setTitleText("SUCCESS")
                                            .setContentText("履约成功")
                                            .setPositiveListener("OK", new PromptDialog.OnPositiveListener() {
                                                @Override
                                                public void onClick(PromptDialog dialog) {
                                                    Bundle bundle = new Bundle();
                                                    bundle.putString("idCard", idCard);
                                                    bundle.putString("servicePackagesId", servicePackagesId);
                                                    bundle.putString("serviceItemId", serviceItemId);
                                                    Navigation.findNavController(v).navigate(R.id.action_FulfillmentitemAddFragment_to_FulfillmentitemFragment,bundle);
                                                    dialog.dismiss();
                                                }
                                            }).show();
                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(String errorMessage) {
                        // 处理签约失败的逻辑
                    }
                });
                insertFulfillmentApi.performInsertFulfillment(servicePackagesId,serviceItemId,idCard,result,day_select.getText().toString(),day_nextselect.getText().toString(),fulfillment_Contract.getText().toString(),Tv_Efficiency.getText().toString());
            }
        });
        servic_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("idCard", idCard);
                bundle.putString("servicePackagesId", servicePackagesId);
                bundle.putString("serviceItemId", serviceItemId);
                Navigation.findNavController(v).navigate(R.id.action_FulfillmentitemAddFragment_to_FulfillmentitemFragment,bundle);
            }
        });
        return root;
    }

    @Override
    public void onResume() {
        BottomNavigationView bottomNavigationView = requireActivity().findViewById(R.id.nav_view);
        bottomNavigationView.setVisibility(View.INVISIBLE);
        //这两行代码设置隐藏底部导航栏，若要显示啧修改INVISIBLE为Visible（可见）
        super.onResume();
    }

    GetfulfillmentAddDataCallback getfulfillmentAddDataCallback = new GetfulfillmentAddDataCallback() {
        @Override
        public void onSuccess(ResponseBody<FulfillmentAddData> responseBody) {
            if (responseBody != null && responseBody.getData() != null) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // Create a bundle to carry the data
                        Tv_name.setText(responseBody.getData().getFulfillmentName());
                        Tv_sex.setText(responseBody.getData().getSex());
                        Tv_phone.setText(responseBody.getData().getTelephone());
                        Tv_Id.setText(responseBody.getData().getIdcard());
                        Tv_doctorsTeam.setText(responseBody.getData().getDoctorName());
                        Tv_Servicename.setText(responseBody.getData().getFulfillmentServiceName());
                        Tv_serviceItemsName.setText(responseBody.getData().getFulfillmentServiceItemName());
                    }
                });
            }
        }

        @Override
        public void onFailure(String errorMessage) {
            // 处理签约失败的逻辑
        }
    };
}
